package com.lh.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lh.config.properties.CsunProperties;
import com.lh.entity.table.*;
import com.lh.entity.vo.TicketProblemPercentVo;
import com.lh.mapper.*;
import com.lh.service.TicketProblemInfoService;
import com.lh.utils.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.DataFormat;
import org.apache.poi.ss.util.CellRangeAddressList;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.text.DecimalFormat;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
public class TicketProblemInfoServiceImpl implements TicketProblemInfoService {

    private LogUtil LOG = new LogUtil(TicketProblemInfoServiceImpl.class);

    @Resource
    private TicketProblemInfoMapper ticketProblemInfoMapper;

    @Resource
    private ProcessNodeMapper processNodeMapper;

    @Resource
    private OSSManageUtil ossManageUtil;

    @Resource
    private CsunProperties csunProperties;

    @Resource
    private ProblemSummaryInfoMapper problemSummaryInfoMapper;

    @Resource
    private DepartmentInfoMapper departmentInfoMapper;

    @Resource
    private TicketProblemPercentMapper ticketProblemPercentMapper;

    @Resource
    private DeadlineNodeMapper deadlineNodeMapper;

//    @Autowired
//    private ActivitiProcessCore activitiProcessCore;

    @Resource
    private ReminderInfoMapper reminderInfoMapper;


    @Override
    public Answer<Object> addTicketProblemInfo(TicketProblemInfo ticketProblemInfo) {
        try {
            Integer task2Id = ticketProblemInfo.getTask2Id();
            Integer summaryId = ticketProblemInfo.getSummaryId();
            String processHandlerDepartment = ticketProblemInfo.getProcessHandlerDepartment();
            if (task2Id==null) {
                return Answer.error("问题汇总id不能为空");
            }
            if (summaryId==null) {
                return Answer.error("问题大类id不能为空");
            }
            if (StrUtil.isNotBlank(processHandlerDepartment)) {
                List<DepartmentInfo> departmentInfoList = departmentInfoMapper.selectList(new LambdaQueryWrapper<DepartmentInfo>().eq(DepartmentInfo::getDepartmentName, processHandlerDepartment));
                if (CollectionUtil.isNotEmpty(departmentInfoList)) {
                    String areaName = departmentInfoList.get(0).getAreaName();
                    ticketProblemInfo.setAreaName(areaName);
                }
            }
            ProblemSummaryInfo problemSummaryInfo = problemSummaryInfoMapper.selectById(summaryId);
            if (problemSummaryInfo == null) {
                return Answer.error("问题汇总不存在");
            }
            String summaryNo = problemSummaryInfo.getSummaryNo();
            List<TicketProblemInfo> existTicketProblemInfoList = ticketProblemInfoMapper.selectList(new LambdaQueryWrapper<TicketProblemInfo>().eq(TicketProblemInfo::getSummaryId, summaryId));
            if (CollectionUtil.isNotEmpty(existTicketProblemInfoList)){
                Collections.sort(existTicketProblemInfoList, Comparator.comparing(TicketProblemInfo::getTicketNo).reversed());
                String lastTicketNo = existTicketProblemInfoList.get(0).getTicketNo();
                ticketProblemInfo.setTicketNo(Convert.toStr(Convert.toInt(lastTicketNo) + 1));
            }else{
                String ticketNo = summaryNo + "0001";
                ticketProblemInfo.setTicketNo(ticketNo);
            }

            Date date = new Date();
            ProcessNode processNode = new ProcessNode();
            String nodeName = ticketProblemInfo.getNodeName();
            ticketProblemInfo.setCreatedTime(date);
            ticketProblemInfoMapper.insert(ticketProblemInfo);
            Integer id = ticketProblemInfo.getId();

            processNode.setTicketId(id);
            processNode.setNodeContent(ticketProblemInfo.getContent());
            processNode.setNodeOwnerId(ticketProblemInfo.getProcessHandlerId());
            processNode.setNodeOwnerName(ticketProblemInfo.getProcessHandlerName());
            processNode.setNodeStatus("1");
            processNode.setNodeName(nodeName);
            processNode.setAnnexFile(ticketProblemInfo.getAnnexFile());
            processNode.setCreatedTime(date);
            processNode.setDepartment(ticketProblemInfo.getProcessHandlerDepartment());
            ticketProblemInfo.setProcessNodeName(nodeName);
            processNodeMapper.insert(processNode);

            ReminderInfo reminderInfo = new ReminderInfo();
            reminderInfo.setReminderTitle("新的任务，请查收");
            reminderInfo.setReminderContent("您有新的任务，任务概括【"+ticketProblemInfo.getProminentIssue()+"】，请注意查收！");
            reminderInfo.setReminderType(1);
            reminderInfo.setReminderTime(date);
            reminderInfo.setRiskLevel(ticketProblemInfo.getRiskLevel());
            reminderInfo.setCompleteDeadline(ticketProblemInfo.getCompleteDeadline());
            reminderInfo.setReminderPerson(ticketProblemInfo.getProcessHandlerName());
            reminderInfo.setReminderDepart(ticketProblemInfo.getProcessHandlerDepartment());
            reminderInfoMapper.insert(reminderInfo);
            Map<String,Object> nextAssigneeMap = new HashMap<>();
            nextAssigneeMap.put("qtdw",ticketProblemInfo.getProcessHandlerName());
//            boolean b = activitiProcessCore.startProcess(Convert.toStr(id), nextAssigneeMap);
//            if (!b){
//                return Answer.error("启动流程失败");
//            }
            return Answer.ok(ticketProblemInfo.getId());
        } catch (Exception e) {
            e.printStackTrace();
            return LOG.error(Answer.build(), "请求addTicketProblemInfo失败！", e);
        }
    }

    @Override
    public Answer<Object> addTicketProblemInfoList(JSONObject reqJson) {
        JSONArray dataList = reqJson.getJSONArray("data");
        if (CollectionUtil.isNotEmpty(dataList)) {
            for (int i = 0; i < dataList.size(); i++) {
                try {
                    TicketProblemInfo ticketProblemInfo = dataList.getObject(i, TicketProblemInfo.class);
                    addTicketProblemInfo(ticketProblemInfo);
                } catch (Exception e) {
                    continue;
                }
            }
        }
        return Answer.ok("请求成功");
    }

    @Override
    public Answer<Object> updateTicketProblemInfo(TicketProblemInfo ticketProblemInfo) {
        try {
            Integer id = ticketProblemInfo.getId();
            if (id == null) {
                return Answer.error("id不能为空");
            }
            ticketProblemInfoMapper.updateById(ticketProblemInfo);
            return Answer.ok("请求成功");
        } catch (Exception e) {
            return LOG.error(Answer.build(), "请求updateTicketProblemInfo失败！", e);
        }
    }

    @Override
    public Answer<Object> deleteTicketProblemInfo(TicketProblemInfo ticketProblemInfo) {
        try {
            Integer id = ticketProblemInfo.getId();
            if (id == null) {
                return Answer.error("id不能为空");
            }
            ticketProblemInfoMapper.deleteById(id);
            return Answer.ok("请求成功");
        } catch (Exception e) {
            return LOG.error(Answer.build(), "请求deleteTicketProblemInfo失败！", e);
        }
    }

    @Override
    public Answer<Object> selectTicketProblemInfo(TicketProblemInfo ticketProblemInfo) {
        try {
            Integer id = ticketProblemInfo.getId();
            if (id == null) {
                return Answer.error("id不能为空");
            }
            TicketProblemInfo result = ticketProblemInfoMapper.selectById(id);
            // 确保附件字段被返回
            return Answer.ok(result);
        } catch (Exception e) {
            return LOG.error(Answer.build(), "查询工单详情失败", e);
        }
    }

    @Override
    public Answer<Object> selectTicketProblemInfoList(JSONObject reqJson) {
        try {
            DecimalFormat df = new DecimalFormat("0.00%");
            List<Object> resList = CollectionUtil.newArrayList();
            String group = reqJson.getString("group");
            String areaName = reqJson.getString("areaName");
            String processHandlerDepartment = reqJson.getString("processHandlerDepartment");
            String prominentIssue = reqJson.getString("prominentIssue");
            String issueType = reqJson.getString("issueType");

            LambdaQueryWrapper<TicketProblemInfo> ticketProblemInfoLambdaQueryWrapper = new LambdaQueryWrapper<>();
            if (StrUtil.isNotBlank(areaName)){
                ticketProblemInfoLambdaQueryWrapper.eq(TicketProblemInfo::getAreaName,areaName);
            }
            if (StrUtil.isNotBlank(processHandlerDepartment)){
                ticketProblemInfoLambdaQueryWrapper.eq(TicketProblemInfo::getProcessHandlerDepartment,processHandlerDepartment);
            }
            if (StrUtil.isNotBlank(prominentIssue)){
                ticketProblemInfoLambdaQueryWrapper.eq(TicketProblemInfo::getProminentIssue,prominentIssue);
            }
            if (StrUtil.isNotBlank(issueType)){
                ticketProblemInfoLambdaQueryWrapper.eq(TicketProblemInfo::getIssueType,issueType);
            }
            List<TicketProblemInfo> ticketProblemInfos = ticketProblemInfoMapper.selectList(ticketProblemInfoLambdaQueryWrapper);
            if ("areaName".equals(group)){
                List<String> areaNameList = ticketProblemInfos.stream().map(TicketProblemInfo::getAreaName).distinct().filter(StrUtil::isNotBlank).collect(Collectors.toList());
                for (String area : areaNameList) {
                    JSONObject json = new JSONObject();
                    List<TicketProblemInfo> collect = ticketProblemInfos.stream().filter(TicketProblemInfo -> TicketProblemInfo.getAreaName() != null && TicketProblemInfo.getAreaName().equals(area)).collect(Collectors.toList());
                    int field1 = collect.size();
                    long field2 = collect.stream().filter(ticketProblemInfo -> ticketProblemInfo.getStatus() != null && !ticketProblemInfo.getStatus().equals("1")).count();

                    json.put("areaName",area);
                    json.put("field1",field1);
                    json.put("field2",Convert.toInt(field2));
                    json.put("proportion",Convert.toInt(field1) == 0 ? "0.00%" : df.format((double) Convert.toInt(field2)  / Convert.toInt(field1)));
                    resList.add(json);
                }
            }else if ("processHandlerDepartment".equals(group)){
                List<String> processHandlerDepartmentList = ticketProblemInfos.stream().map(TicketProblemInfo::getProcessHandlerDepartment).distinct().filter(StrUtil::isNotBlank).collect(Collectors.toList());
                for (String department : processHandlerDepartmentList) {
                    JSONObject json = new JSONObject();
                    List<TicketProblemInfo> collect = ticketProblemInfos.stream().filter(TicketProblemInfo -> TicketProblemInfo.getProcessHandlerDepartment() != null && TicketProblemInfo.getProcessHandlerDepartment().equals(department)).collect(Collectors.toList());
                    int field1 = collect.size();
                    long field2 = collect.stream().filter(ticketProblemInfo -> ticketProblemInfo.getStatus() != null && !ticketProblemInfo.getStatus().equals("1")).count();

                    json.put("areaName",department);
                    json.put("field1",field1);
                    json.put("field2",Convert.toInt(field2));
                    json.put("proportion",Convert.toInt(field1) == 0 ? "0.00%" : df.format((double) Convert.toInt(field2)  / Convert.toInt(field1)));
                    resList.add(json);
                }
            }

            return Answer.ok(resList);
        } catch (Exception e) {
            e.printStackTrace();
            return LOG.error(Answer.build(), "请求selectTicketProblemInfoList失败！", e);
        }
    }

    @Override
    public Answer<Object> selectTicketProblemInfoPage(JSONObject reqJson) {
        try {
            Integer pageSize = reqJson.getInteger("pageSize");
            Integer pageNum = reqJson.getInteger("pageNum");
            Page<TicketProblemInfo> page = new Page<>(pageNum, pageSize);

            LambdaQueryWrapper<TicketProblemInfo> ticketProblemInfoLambdaQueryWrapper = new LambdaQueryWrapper<>();
            String ticketNo = reqJson.getString("ticketNo");
            if (StrUtil.isNotBlank(ticketNo)) {
                ticketProblemInfoLambdaQueryWrapper.eq(TicketProblemInfo::getTicketNo,ticketNo);
            }
            String content = reqJson.getString("content");
            if (StrUtil.isNotBlank(content)) {
                ticketProblemInfoLambdaQueryWrapper.like(TicketProblemInfo::getContent,content);
            }
            String riskLevel = reqJson.getString("riskLevel");
            if (StrUtil.isNotBlank(riskLevel)) {
                ticketProblemInfoLambdaQueryWrapper.eq(TicketProblemInfo::getRiskLevel,riskLevel);
            }
            String status = reqJson.getString("status");
            if (StrUtil.isNotBlank(status)) {
                ticketProblemInfoLambdaQueryWrapper.eq(TicketProblemInfo::getStatus,status);
            }
            String isEvaluate = reqJson.getString("isEvaluate");
            if (StrUtil.isNotBlank(isEvaluate)) {
                ticketProblemInfoLambdaQueryWrapper.eq(TicketProblemInfo::getIsEvaluate,isEvaluate);
            }
            String processHandlerDepartment = reqJson.getString("processHandlerDepartment");
            if (StrUtil.isNotBlank(processHandlerDepartment)) {
                ticketProblemInfoLambdaQueryWrapper.eq(TicketProblemInfo::getProcessHandlerDepartment,processHandlerDepartment).or().eq(TicketProblemInfo::getLeadUnit,processHandlerDepartment);
            }
            String processHandlerName = reqJson.getString("processHandlerName");
            if (StrUtil.isNotBlank(processHandlerName)) {
                ticketProblemInfoLambdaQueryWrapper.eq(TicketProblemInfo::getProcessHandlerName,processHandlerName);
            }
            String processNodeName = reqJson.getString("processNodeName");
            if (StrUtil.isNotBlank(processNodeName)) {
                ticketProblemInfoLambdaQueryWrapper.eq(TicketProblemInfo::getProcessNodeName,processNodeName);
            }
            String issueType = reqJson.getString("issueType");
            if (StrUtil.isNotBlank(issueType)) {
                ticketProblemInfoLambdaQueryWrapper.eq(TicketProblemInfo::getIssueType,issueType);
            }
            String issueCategory = reqJson.getString("issueCategory");
            if (StrUtil.isNotBlank(issueCategory)) {
                ticketProblemInfoLambdaQueryWrapper.eq(TicketProblemInfo::getIssueCategory,issueCategory);
            }
            String prominentIssue = reqJson.getString("prominentIssue");
            if (StrUtil.isNotBlank(prominentIssue)) {
                ticketProblemInfoLambdaQueryWrapper.eq(TicketProblemInfo::getProminentIssue,prominentIssue);
            }
            String applicantName = reqJson.getString("applicantName");
            if (StrUtil.isNotBlank(applicantName)) {
                ticketProblemInfoLambdaQueryWrapper.eq(TicketProblemInfo::getApplicantName,applicantName);
            }
            String applicantPhoneNumber = reqJson.getString("applicantPhoneNumber");
            if (StrUtil.isNotBlank(applicantPhoneNumber)) {
                ticketProblemInfoLambdaQueryWrapper.eq(TicketProblemInfo::getApplicantPhoneNumber,applicantPhoneNumber);
            }
            String processHandlerId = reqJson.getString("processHandlerId");
            if (StrUtil.isNotBlank(processHandlerId)) {
                ticketProblemInfoLambdaQueryWrapper.eq(TicketProblemInfo::getProcessHandlerId,processHandlerId);
            }
            String issueSubCategory = reqJson.getString("issueSubCategory");
            if (StrUtil.isNotBlank(issueSubCategory)) {
                ticketProblemInfoLambdaQueryWrapper.eq(TicketProblemInfo::getIssueSubCategory,issueSubCategory);
            }
            String appealName = reqJson.getString("appealName");
            if (StrUtil.isNotBlank(appealName)) {
                ticketProblemInfoLambdaQueryWrapper.eq(TicketProblemInfo::getAppealName,appealName);
            }
            String appealPhoneNumber = reqJson.getString("appealPhoneNumber");
            if (StrUtil.isNotBlank(appealPhoneNumber)) {
                ticketProblemInfoLambdaQueryWrapper.eq(TicketProblemInfo::getAppealPhoneNumber,appealPhoneNumber);
            }
            String dataResource = reqJson.getString("dataResource");
            if (StrUtil.isNotBlank(dataResource)) {
                ticketProblemInfoLambdaQueryWrapper.eq(TicketProblemInfo::getDataResource,dataResource);
            }
            ticketProblemInfoLambdaQueryWrapper.ne(TicketProblemInfo::getStatus,"0");
            ticketProblemInfoLambdaQueryWrapper.orderByDesc(TicketProblemInfo::getId);

            Page<TicketProblemInfo> Page = ticketProblemInfoMapper.selectPage(page,ticketProblemInfoLambdaQueryWrapper);
            List<TicketProblemInfo> list = Page.getRecords();
            for (TicketProblemInfo info : list) {
                List<TicketProblemPercent> ticketProblemPercentList = ticketProblemPercentMapper.selectList(new LambdaQueryWrapper<TicketProblemPercent>().eq(TicketProblemPercent::getTicketProblemInfoId, info.getId()));
                List<TicketProblemPercentVo> ticketProblemPercentVoList = ticketProblemPercentList.stream().map(ticketProblemPercent -> {
                    TicketProblemPercentVo ticketProblemPercentVo = new TicketProblemPercentVo();
                    BeanUtils.copyProperties(ticketProblemPercent, ticketProblemPercentVo);
                    return ticketProblemPercentVo;
                }).collect(Collectors.toList());
                info.setTicketProblemPercentVoList(ticketProblemPercentVoList);
                List<DeadlineNode> deadlineNodeList = deadlineNodeMapper.selectList(new LambdaQueryWrapper<DeadlineNode>().eq(DeadlineNode::getMainId, info.getId()).eq(DeadlineNode::getTypeName, "下发").orderByAsc(DeadlineNode::getSort));
                info.setDeadlineNodeList(deadlineNodeList);
            }
            Collections.sort(list, Comparator.comparing(TicketProblemInfo::getId).reversed());
            return Answer.ok(Page);
        } catch (Exception e) {
            e.printStackTrace();
            return Answer.error(e.getMessage());
        }
    }

    @Override
    public Answer<Object> processIssuance(JSONObject reqJson) {
        try {
            DateTime date = DateUtil.date();
            Integer id = reqJson.getInteger("id");
            String processNodeName = reqJson.getString("processNodeName");
            String completeDescription = reqJson.getString("completeDescription");
            String processHandlerId = reqJson.getString("processHandlerId");
            String processHandlerName = reqJson.getString("processHandlerName");
            String processHandlerDepartment = reqJson.getString("processHandlerDepartment");
            String annexFile = reqJson.getString("annexFile");
            String rectificationObjective = reqJson.getString("rectificationObjective");
            String rectificationMeasure = reqJson.getString("rectificationMeasure");
            String acceptanceCriteria = reqJson.getString("acceptanceCriteria");
            Date completeDeadline = reqJson.getDate("completeDeadline");
            String issueType = reqJson.getString("issueType");
            JSONArray participantsList = reqJson.getJSONArray("participantsList");
            Date meetDeadline = reqJson.getDate("meetDeadline");
            Date meetTime = reqJson.getDate("meetTime");
            JSONArray actuallyParticipantsList = reqJson.getJSONArray("actuallyParticipantsList");

            if (id == null) {
                return Answer.error("id不能为空");
            }

            TicketProblemInfo queryTicketProblemInfo = ticketProblemInfoMapper.selectById(id);
            if (queryTicketProblemInfo == null) {
                return Answer.error("工单不存在");
            }

            ProcessNode processNode = new ProcessNode();
            List<ProcessNode> processNodeList = processNodeMapper.selectList(new LambdaQueryWrapper<ProcessNode>().eq(ProcessNode::getTicketId,id));
            if (CollectionUtil.isNotEmpty(processNodeList)) {
                Collections.sort(processNodeList, Comparator.comparing(ProcessNode::getCreatedTime).reversed());
                ProcessNode processNodeOld = processNodeList.get(0);
                processNodeOld.setEndTime(date);
                processNodeOld.setNodeStatus("0");
                processNodeMapper.updateById(processNodeOld);
                processNode.setParentId(processNodeOld.getId());
            }
            processNode.setTicketId(id);
            processNode.setNodeName(processNodeName);
            processNode.setNodeContent(completeDescription);
            processNode.setNodeOwnerId(processHandlerId);
            processNode.setNodeOwnerName(processHandlerName);
            processNode.setDepartment(processHandlerDepartment);
            processNode.setAnnexFile(annexFile);
            processNode.setNodeStatus("1");
            processNode.setCreatedTime(date);
            if(CollectionUtil.isNotEmpty(participantsList)){
                queryTicketProblemInfo.setParticipants(CollectionUtil.join(participantsList,","));
                processNode.setParticipants(CollectionUtil.join(participantsList,","));
            }
            if(meetDeadline != null){
                queryTicketProblemInfo.setMeetDeadline(meetDeadline);
                processNode.setMeetDeadline(meetDeadline);
            }
            if(meetTime != null){
                queryTicketProblemInfo.setMeetTime(meetTime);
                processNode.setMeetTime(meetTime);
            }
            if(CollectionUtil.isNotEmpty(actuallyParticipantsList)){
                queryTicketProblemInfo.setActuallyParticipants(CollectionUtil.join(actuallyParticipantsList,","));
                processNode.setActuallyParticipants(CollectionUtil.join(actuallyParticipantsList,","));
            }
            processNodeMapper.insert(processNode);

            if(StrUtil.isNotBlank(processHandlerId)){
                queryTicketProblemInfo.setProcessHandlerId(processHandlerId);
            }
            if(StrUtil.isNotBlank(processHandlerName)){
                queryTicketProblemInfo.setProcessHandlerName(processHandlerName);
            }
            if(StrUtil.isNotBlank(processNodeName)){
                queryTicketProblemInfo.setProcessNodeName(processNodeName);
            }
            if(StrUtil.isNotBlank(processHandlerDepartment)){
                queryTicketProblemInfo.setProcessHandlerDepartment(processHandlerDepartment);
            }
            if(StrUtil.isNotBlank(completeDescription)){
                queryTicketProblemInfo.setCompleteDescription(completeDescription);
            }
            if(StrUtil.isNotBlank(rectificationObjective)){
                queryTicketProblemInfo.setRectificationObjective(rectificationObjective);
            }
            if(StrUtil.isNotBlank(rectificationMeasure)){
                queryTicketProblemInfo.setRectificationMeasure(rectificationMeasure);
            }
            if(StrUtil.isNotBlank(acceptanceCriteria)){
                queryTicketProblemInfo.setAcceptanceCriteria(acceptanceCriteria);
            }
            if(completeDeadline != null){
                queryTicketProblemInfo.setCompleteDeadline(completeDeadline);
            }
            if (issueType != null){
                queryTicketProblemInfo.setIssueType(issueType);
            }

            ticketProblemInfoMapper.updateById(queryTicketProblemInfo);
//            Map<String, Object> nextAssigneeMap = new HashMap<>();
//            nextAssigneeMap.put("qtdw","qtdw_lalala");
//            nextAssigneeMap.put("shyj1","0");
//            boolean b = activitiProcessCore.completTask(Convert.toStr(queryTicketProblemInfo.getId()), queryTicketProblemInfo.getProcessHandlerName(), completeDescription, null);
//            if (!b){
//                return Answer.error("启动流程失败");
//            }
            return Answer.ok("请求成功");
        } catch (Exception e) {
            e.printStackTrace();
            return Answer.error(e.getMessage());
        }
    }

    @Override
    public Answer<Object> processBack(TicketProblemInfo ticketProblemInfo) {
        try {
            Integer id = ticketProblemInfo.getId();
            if (id == null) {
                return Answer.error("id不能为空");
            }
            TicketProblemInfo queryTicketProblemInfo = ticketProblemInfoMapper.selectById(id);
            if (queryTicketProblemInfo == null) {
                return Answer.error("工单不存在");
            }
            queryTicketProblemInfo.setStatus("2");
            queryTicketProblemInfo.setEndTime(DateUtil.date());
            ticketProblemInfoMapper.updateById(queryTicketProblemInfo);
            return Answer.ok("请求成功");
        } catch (Exception e) {
            return Answer.error(e.getMessage());
        }
    }

    @Override
    public Answer<Object> queryNodeList(JSONObject reqJson) {
        try {
            Integer id = reqJson.getInteger("ticket_id");
            if (id == null) {
                return Answer.error("id不能为空");
            }
            List<ProcessNode> processNodeList = processNodeMapper.selectList(new LambdaQueryWrapper<ProcessNode>().eq(ProcessNode::getTicketId,id));
            return Answer.ok(processNodeList);
        } catch (Exception e) {
            return Answer.error(e.getMessage());
        }
    }

    @Override
    public Answer<Object> updateNodeList(ProcessNode processNode) {
        try {
            Integer id = processNode.getId();
            if (id == null) {
                return Answer.error("id不能为空");
            }
            processNodeMapper.updateById(processNode);
            return Answer.ok("请求成功");
        } catch (Exception e) {
            return Answer.error(e.getMessage());
        }
    }

    @Override
    public Answer<Object> processEnd(JSONObject reqJson) {
        try {
            Integer id = reqJson.getInteger("id");
            String evaluateContent = reqJson.getString("evaluateContent");
            if (id == null) {
                return Answer.error("id不能为空");
            }
            TicketProblemInfo queryTicketProblemInfo = ticketProblemInfoMapper.selectById(id);
            if (queryTicketProblemInfo == null) {
                return Answer.error("工单不存在");
            }
            DateTime date = DateUtil.date();
            List<ProcessNode> processNodeList = processNodeMapper.selectList(new LambdaQueryWrapper<ProcessNode>().eq(ProcessNode::getTicketId,id));
            if (CollectionUtil.isNotEmpty(processNodeList)) {
                Collections.sort(processNodeList, Comparator.comparing(ProcessNode::getCreatedTime).reversed());
                ProcessNode processNode = processNodeList.get(0);
                processNode.setNodeStatus("2");
                processNode.setEndTime(date);
                processNodeMapper.updateById(processNode);
                ProcessNode processNodeEnd = new ProcessNode();

                processNodeEnd.setTicketId(id);
                processNodeEnd.setNodeName("已结束");
                processNodeEnd.setNodeStatus("2");
                processNodeEnd.setCreatedTime(date);
                processNodeEnd.setEndTime(date);

            } else {
                return Answer.error("节点不存在");
            }
            queryTicketProblemInfo.setEvaluateTime(date);
            queryTicketProblemInfo.setIsEvaluate("1");
            queryTicketProblemInfo.setEvaluateScore("0");
            queryTicketProblemInfo.setEvaluateContent(evaluateContent);
            queryTicketProblemInfo.setEndTime(date);
            queryTicketProblemInfo.setStatus("2");
            queryTicketProblemInfo.setProcessNodeName("已结束");
            ticketProblemInfoMapper.updateById(queryTicketProblemInfo);
            return Answer.ok("请求成功");
        } catch (Exception e) {
            return Answer.error(e.getMessage());
        }
    }

    @Override
    public Answer<Object> uploadFile(HttpServletRequest request) {
        try {
            /* 获取文件描述参数和关联ID */
            String remark = request.getParameter("remark");
            // 获取关联的工单ID（根据实际业务调整参数名）
            Integer ticketId = Convert.toInt(request.getParameter("ticketId"), 0);
            List<DsmsResource> resources = new ArrayList<DsmsResource>();
            List<String> fileUrls = new ArrayList<>(); // 存储本次上传的文件URL

            /* 将当前上下文初始化给  CommonsMutipartResolver （多部分解析器）*/
            CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
                    request.getSession().getServletContext());

            /* 检查form中是否有enctype="multipart/form-data" */
            if (multipartResolver.isMultipart(request)) {
                /* 将request变成多部分request */
                MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;

                /* 获取multiRequest 中所有的文件名*/
                Iterator iter = multiRequest.getFileNames();
                String timedate = Convert.toStr(DateUtil.current()); // 时间戳,避免文件覆盖

                while (iter.hasNext()) {
                    // 一次遍历所有文件
                    MultipartFile file = multiRequest.getFile(iter.next().toString());
                    if (file != null) {
                        /* 文件属性获取 */
                        SourceType sourceType = MimeTypeUtil.getSourceType(file.getContentType());
                        /* MultipartFile 转 File */
                        File f = File.createTempFile("tmp", null);
                        file.transferTo(f);
                        f.deleteOnExit();
                        /* OSS文件上传 */
                        ossManageUtil.uploadFile(f, file.getOriginalFilename(), file.getContentType(), sourceType
                                .getSourceTypePath() + "/" + timedate);
                        /* 保存上传的文件属性 */
                        DsmsResource r = new DsmsResource();
                        r.setResourceName(file.getOriginalFilename());
                        String fileUrl = csunProperties.getAliyun().getOss().getAccessUrl() + "/"
                                + sourceType.getSourceTypePath() + "/" + timedate + "/" + file.getOriginalFilename();
                        r.setResourcePath(fileUrl);
                        fileUrls.add(fileUrl); // 收集本次上传的URL

                        if (StrUtil.isNotBlank(remark)) {
                            r.setRemark(remark);
                        }
                        r.setResourceTypeId(Integer.parseInt(sourceType.getSourceTypeId()));
                        resources.add(r);
                    }
                }
            }

            // 如果有工单ID，更新对应的实体附件信息
            if (ticketId > 0) {
                TicketProblemInfo ticketProblemInfo = ticketProblemInfoMapper.selectById(ticketId);
                if (ticketProblemInfo != null) {
                    // 获取已有附件URL
                    String existingUrls = ticketProblemInfo.getAnnexFile();
                    // 拼接新上传的URL，用逗号分隔
                    StringBuilder newUrls = new StringBuilder();
                    if (StrUtil.isNotBlank(existingUrls)) {
                        newUrls.append(existingUrls).append(",");
                    }
                    newUrls.append(String.join(",", fileUrls));
                    // 更新附件URL
                    ticketProblemInfo.setAnnexFile(newUrls.toString());
                    ticketProblemInfoMapper.updateById(ticketProblemInfo);
                }
            }

            return Answer.ok(resources);
        } catch (Exception e) {
            return Answer.error(e.getMessage());
        }
    }

    @Override
    public void downTicketProblemExcelData(HttpServletResponse response, JSONObject reqJson) {
        try {
            String prominentIssue = reqJson.getString("prominentIssue");
            List<String> row = CollUtil.newArrayList("突出问题类型", "问题内容", "问题来源", "来源描述",
                    "完成时限", "完成要求", "牵头单位","责任单位","备注");
            List<List<String>> rows = CollUtil.newArrayList(row, CollUtil.newArrayList());
            ExcelWriter writer = ExcelUtil.getWriter(true);
            writer.write(rows, true);

            //设置宽度20
            for (int i = 0; i < row.size(); i++) {
                writer.setColumnWidth(i, 20);
            }
            CellStyle dateStyle = writer.createCellStyle();
            DataFormat dataFormat = writer.getWorkbook().createDataFormat();
            dateStyle.setDataFormat(dataFormat.getFormat("yyyy-MM-dd")); // 设置日期格式
            writer.setColumnStyle(5, dateStyle);

            CellRangeAddressList region0 = new CellRangeAddressList(1, 1000, 0, 0);
            writer.addSelect(region0,prominentIssue);

            List<ProblemSummaryInfo> jyProblemDetails = problemSummaryInfoMapper.selectList(new LambdaQueryWrapper<ProblemSummaryInfo>().eq(ProblemSummaryInfo::getProminentIssue, prominentIssue));
            if(CollectionUtil.isNotEmpty(jyProblemDetails)){
                ProblemSummaryInfo problemSummaryInfo = jyProblemDetails.get(0);
                String leadUnit = problemSummaryInfo.getLeadUnit();
                CellRangeAddressList region6 = new CellRangeAddressList(1, 1000, 6, 6);
                writer.addSelect(region6,leadUnit);
            }

            CellRangeAddressList region3 = new CellRangeAddressList(1, 1000, 2, 2);
            writer.addSelect(region3,"上级交办","群众投诉","干部自查");



            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
            response.setHeader("Content-Disposition", "attachment;filename=ExcelData.xlsx");
            ServletOutputStream out = response.getOutputStream();
            writer.flush(out, true);
            writer.close();
            IoUtil.close(out);
        } catch (Exception e) {
            log.error("下载模板数据报错", e);
        }
    }

    @Override
    public Answer<Object> importTicketProblemInfo(MultipartFile file) {
        try {
            ExcelReader reader = ExcelUtil.getReader(file.getInputStream());
            List<Map<String, Object>> ExcelList = reader.readAll();
            if (CollectionUtil.isEmpty(ExcelList)) {
                return Answer.error("Excel不能为空！");
            }
            DateTime date = DateUtil.date();
            for (Map<String, Object> map : ExcelList) {
                TicketProblemInfo ticketProblemInfo = new TicketProblemInfo();
                ProcessNode processNode = new ProcessNode();

                String prominentIssue = Convert.toStr(map.get("突出问题类型"));
                String content = Convert.toStr(map.get("问题内容"));
                String dataResource = Convert.toStr(map.get("问题来源"));
                String resourceDescription = Convert.toStr(map.get("来源描述"));
                Date completeDeadline = Convert.toDate(map.get("完成时限"));
                String completeDescription = Convert.toStr(map.get("完成要求"));
                String remark = Convert.toStr(map.get("备注"));
                String leadUnit = Convert.toStr(map.get("牵头单位"));
                String processHandlerDepartment = Convert.toStr(map.get("责任单位"));
                if (StrUtil.isNotBlank(processHandlerDepartment)) {
                    DepartmentInfo departmentInfo = departmentInfoMapper.selectOne(new LambdaQueryWrapper<DepartmentInfo>().eq(DepartmentInfo::getDepartmentName, processHandlerDepartment));
                    if (departmentInfo!=null) {
                        String areaName = departmentInfo.getAreaName();
                        ticketProblemInfo.setAreaName(areaName);
                    }
                    ticketProblemInfo.setProcessHandlerDepartment(processHandlerDepartment);
                    ticketProblemInfo.setProcessNodeName("待受理");
                    processNode.setDepartment(processHandlerDepartment);
                    processNode.setNodeName("待受理");
                }else{
                    ticketProblemInfo.setProcessNodeName("待分拨");
                    processNode.setNodeName("待分拨");
                }
                processNode.setRemark("系统导入");
                processNode.setNodeContent(completeDescription);
                processNode.setNodeStatus("1");

                ticketProblemInfo.setProminentIssue(prominentIssue);
                ticketProblemInfo.setTitle(prominentIssue);
                ticketProblemInfo.setContent(content);
                ticketProblemInfo.setDataResource(dataResource);
                ticketProblemInfo.setResourceDescription(resourceDescription);
                ticketProblemInfo.setCompleteDeadline(completeDeadline);
                ticketProblemInfo.setCompleteDescription(completeDescription);
                ticketProblemInfo.setRemark(remark);
                ticketProblemInfo.setLeadUnit(leadUnit);
                ticketProblemInfo.setRiskLevel("1");
                ticketProblemInfo.setCreatedTime(date);
                ticketProblemInfoMapper.insert(ticketProblemInfo);
                processNode.setTicketId(ticketProblemInfo.getId());
                processNode.setCreatedTime(date);
                processNodeMapper.insert(processNode);

            }
            return Answer.ok("请求成功");
        } catch (Exception e) {
            log.error("下载模板数据报错", e);
            return Answer.error("下载模板数据报错");
        }
    }

    @Override
    public Answer<Object> updateDeadlineNode(DeadlineNode deadlineNode) {
        try {
            Integer id = deadlineNode.getId();
            if (id==null){
                return Answer.error("id不能为空");
            }
            deadlineNode.setUpdateTime(new Date());
            deadlineNodeMapper.updateById(deadlineNode);
            return Answer.ok("请求成功");
        } catch (Exception e) {
            log.error("更新时限报错", e);
            return Answer.error("更新时限报错");
        }
    }

}